from typing import List, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status, Request
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
from app.schemas.task import Task, TaskCreate, TaskUpdate
from app.services import task_service
import logging
import traceback

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter()

@router.get("/", response_model=List[Dict[str, Any]])
async def get_tasks(
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db)
):
    """获取任务列表"""
    try:
        tasks = await task_service.get_tasks(db, skip=skip, limit=limit)
        # 将任务列表转换为字典列表
        result = []
        for task in tasks:
            result.append({
                "id": task.id,
                "title": task.title,
                "description": task.description,
                "status": task.status.value if task.status else None,
                "created_at": task.created_at,
                "updated_at": task.updated_at,
                "user_id": task.user_id
            })
        return result
    except Exception as e:
        logger.error(f"获取任务列表失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )

@router.post("/", response_model=Dict[str, Any])
async def create_task(
    request: Request,
    task: TaskCreate,
    db: AsyncSession = Depends(get_db)
):
    """创建新任务"""
    try:
        logger.info(f"创建任务: {task.dict()}")
        body = await request.json()
        logger.info(f"原始请求体: {body}")
        
        db_task = await task_service.create_task(db, task)
        
        # 将数据库模型转换为字典
        task_dict = {
            "id": db_task.id,
            "title": db_task.title,
            "description": db_task.description,
            "status": db_task.status.value if db_task.status else None,
            "created_at": db_task.created_at,
            "updated_at": db_task.updated_at,
            "user_id": db_task.user_id
        }
        
        logger.info(f"返回数据: {task_dict}")
        return task_dict
    except Exception as e:
        logger.error(f"创建任务失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )

@router.get("/{task_id}", response_model=Dict[str, Any])
async def get_task(
    task_id: int,
    db: AsyncSession = Depends(get_db)
):
    """获取单个任务"""
    try:
        task = await task_service.get_task(db, task_id)
        if not task:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Task not found"
            )
            
        # 将数据库模型转换为字典
        task_dict = {
            "id": task.id,
            "title": task.title,
            "description": task.description,
            "status": task.status.value if task.status else None,
            "created_at": task.created_at,
            "updated_at": task.updated_at,
            "user_id": task.user_id
        }
        
        return task_dict
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取任务失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )

@router.put("/{task_id}", response_model=Dict[str, Any])
async def update_task(
    task_id: int,
    task_update: TaskUpdate,
    db: AsyncSession = Depends(get_db)
):
    """更新任务"""
    try:
        task = await task_service.update_task(db, task_id, task_update)
        if not task:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Task not found"
            )
            
        # 将数据库模型转换为字典
        task_dict = {
            "id": task.id,
            "title": task.title,
            "description": task.description,
            "status": task.status.value if task.status else None,
            "created_at": task.created_at,
            "updated_at": task.updated_at,
            "user_id": task.user_id
        }
        
        return task_dict
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新任务失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )

@router.delete("/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_task(
    task_id: int,
    db: AsyncSession = Depends(get_db)
):
    """删除任务"""
    try:
        success = await task_service.delete_task(db, task_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Task not found"
            )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除任务失败: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        ) 